package cn.backpackerxl.easyJDBC.mrss;

import cn.backpackerxl.easyJDBC.annotation.Id;
import cn.backpackerxl.easyJDBC.annotation.IgnoreField;
import cn.backpackerxl.easyJDBC.main.Executor;
import cn.backpackerxl.easyJDBC.util.*;

import java.lang.reflect.Field;
import java.util.UUID;

import static cn.backpackerxl.easyJDBC.util.Logger.logger;
import static cn.backpackerxl.easyJDBC.util.SqlFactory.joinSqlSave;

/**
 * 数据库保存操作
 *
 * @author: backpackerxl
 * @create: 2021/12/23
 * @filename: EasyJDBCSave
 **/
public class EasyJDBCSave {

    /**
     * 保存数据到对应表格中去
     *
     * @param table  表名
     * @param fields 字段名
     * @param obj    操作对象
     * @return 0 -> 注册失败, 1 -> 注册成功
     */
    public int saveToTable(String table, Field[] fields, Object obj) {
        String sql = joinSqlSave(table, fields);
        logger(obj, JDBC.SAVE, sql);
        return Executor.doExecutorByMRS(sql, ps -> ReflectUtil.doWithLocalSQLFields(obj.getClass(), (field, i) -> {
            if (field.isAnnotationPresent(Id.class)) {
                IdType strategy = field.getDeclaredAnnotation(Id.class).strategy();
                switch (strategy) {
                    case UUID:
                        if (!field.getType().equals(String.class)) {
                            throw new IllegalArgumentException("\nfield is a Id and use UUID, so type can't " + field.getType().getName() + ",please change the type to String .");
                        }
                        field.set(obj, UUID.randomUUID().toString());
                        break;
                    case SNOWFLAKE:
                        if (!field.getType().equals(Long.class)) {
                            throw new IllegalArgumentException("\nfield is a Id and use SNOWFLAKE, so type can't " + field.getType().getName() + ",please change the type to long.");
                        }
                        field.set(obj, IdWorker.getIdWork());
                        break;
                    default:
                        break;
                }
                SqlFactory.doSetValue(field, obj, ps, i);
            }
            if (!field.isAnnotationPresent(IgnoreField.class) && !field.isAnnotationPresent(Id.class)) {
                SqlFactory.doSetValue(field, obj, ps, i);
            }
        }));
    }
}
